<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="负责人" prop="rContact" width="80px">
        <el-input
          v-model="queryParams.rContact"
          placeholder="请输入负责人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:retail:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:retail:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:retail:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:retail:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="retailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="80px"/>
      <el-table-column label="负责人姓名" align="center" prop="rContact"/>
      <el-table-column label="合作协议" align="center" prop="agreement">
        <template slot-scope="scope">
          <image-preview :src="scope.row.agreement" :image-width="100" :image-height="100"/>
        </template>
      </el-table-column>
      <el-table-column label="地图位置" align="center">
        <template slot-scope="scope">
    <span @click="showMap(scope.row.rLongitude , scope.row.rLatitude)">
      <el-button
        type="primary"
        plain
        size="mini"
      >查看地图</el-button>
    </span>
        </template>
      </el-table-column>
      <el-table-column label="生产状态" align="center" key="rStatus">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.rStatus"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:retail:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:retail:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改散户信息管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="负责人" prop="rContact">
          <el-input v-model="form.rContact" placeholder="请输入负责人姓名"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="rPhone">
          <el-input v-model="form.rPhone" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="营业执照" prop="agreement">
          <ImageUpload v-model="form.agreement" limit="1"/>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="openMapDialog">在地图中选择位置
          </el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看地图显示 -->
    <el-dialog
      title="地图显示"
      :visible.sync="mapDialogVisible"
      width="70%"
      append-to-body
    >
      <div id="map" style="height: 400px;"></div>
    </el-dialog>

    <!-- 添加或修改供应商信息对话框 -->
    <el-dialog
      title="地图显示"
      :visible.sync="newMapDialogVisible"
      width="70%"
      append-to-body
    >
      <div id="map" style="height: 400px;"></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmLocation">确定</el-button>
        <el-button @click="newMapDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {listRetail, getRetail, delRetail, addRetail, updateRetail, changeRetailStatus} from "@/api/system/retail";
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "Retail",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 散户信息管理表格数据
      retailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      mapDialogVisible: false,
      newMapDialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        rContact: null,
        rPhone: null,
        rLongitude: null,
        rLatitude: null,
        agreement: null,
        rStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        rContact: [
          {required: true, message: "负责人姓名不能为空", trigger: "blur"}
        ],
        rPhone: [
          {required: true, message: "联系电话不能为空", trigger: "blur"}
        ],
        businessLicense: [
          {required: true, message: "营业执照不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询散户信息管理列表 */
    getList() {
      this.loading = true;
      listRetail(this.queryParams).then(response => {
        this.retailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        rId: null,
        supplierId: null,
        rContact: null,
        rLongitude: null,
        rLatitude: null,
        agreement: null,
        rStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.rId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加散户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const rId = row.rId || this.ids
      getRetail(rId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改散户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.rId != null) {
            updateRetail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRetail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const rIds = row.rId || this.ids;
      this.$modal.confirm('是否确认删除散户信息管理编号为"' + rIds + '"的数据项？').then(function () {
        return delRetail(rIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/retail/export', {
        ...this.queryParams
      }, `retail_${new Date().getTime()}.xlsx`)
    },

    openMapDialog() {
      this.newMapDialogVisible = true;
      AMapLoader.load({
        key: '77b44b6f84ac46b347e84a0ee471f45f',
        version: '1.4.15',
        plugins: ['AMap.Geocoder']
      }).then(AMap => {
        const center = this.form.longitude && this.form.latitude
          ? [this.form.longitude, this.form.latitude]
          : [111.56, 40.79];

        this.map = new AMap.Map('map', {
          center,
          zoom: 15
        });

        if (this.form.longitude && this.form.latitude) {
          this.marker = new AMap.Marker({
            position: center,
            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
            map: this.map
          });
        }

        this.map.on('click', (e) => {
          const {lng, lat} = e.lnglat;
          this.mapLocation = {longitude: lng, latitude: lat};

          if (this.marker) {
            this.marker.setPosition([lng, lat]);
          } else {
            this.marker = new AMap.Marker({
              position: [lng, lat],
              icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
              map: this.map
            });
          }
        });
      }).catch(e => {
        console.error("高德地图初始化失败：", e);
      });
    },

    showMap(longitude, latitude) {
      this.mapLocation = {longitude, latitude};
      this.mapDialogVisible = true;
      AMapLoader.load({
        key: '77b44b6f84ac46b347e84a0ee471f45f',
        version: '1.4.15',
        plugins: ['AMap.Geocoder']
      }).then(AMap => {
        const center = longitude && latitude
          ? [longitude, latitude]
          : [111.56, 40.79];

        this.map = new AMap.Map('map', {
          center,
          zoom: 15
        });

        this.marker = new AMap.Marker({
          position: center,
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          map: this.map
        });
      }).catch(e => {
        console.error("高德地图初始化失败：", e);
      });
    },

    confirmLocation() {
      this.form.rLongitude = this.mapLocation.longitude;
      this.form.rLatitude = this.mapLocation.latitude;
      this.newMapDialogVisible = false;
    },
    /** 修改散户生产状态 */
    handleStatusChange(row) {
      let text = row.rStatus === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.rContact + '"负责的散户吗？').then(function () {
        console.log("id", row.rId);
        console.log("status", row.rStatus);
        return changeRetailStatus(row.rId, row.rStatus);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.rStatus = row.rStatus === "0" ? "1" : "0";
      });
    },
  }
};
</script>
